//
//  CZComposeViewController.swift
//  iOSWeibo10
//
//  Created by 李伟鹏 on 16/5/21.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class CZComposeViewController: UIViewController {

    
    private let statusMaxLength = 25
    
    private var isShowPhotoSelectorView = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

       self.view.backgroundColor = GlobalBKGColor
        setupNavigationBar()
        setupTextView()
        setupPhotoSelectorView()
        setupToolBar()
        setupLengthTipLabel()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if !isShowPhotoSelectorView{
            
        self.textView.becomeFirstResponder()
        }
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private func setupPhotoSelectorView(){
        let photoSelectorView = photoSelectorVC.view
        self.view.addSubview(photoSelectorView)
        self.addChildViewController(photoSelectorVC)
        photoSelectorView.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.equalTo(self.view)
            let height = UIScreen.mainScreen().bounds.height * 0.6
            make.height.equalTo(height)
            
            make.bottom.equalTo(self.view).offset(height)
        }

    }
    
    private func setupLengthTipLabel(){
        self.view.addSubview(lengthTipLabel)
        
        lengthTipLabel.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(self.view).offset(-3)
            make.bottom.equalTo(toolBar.snp_top).offset(-3)
        }
    }
    
    func willChangeFrame(notification: NSNotification) {
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        let frame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        let bottomMargin = -(UIScreen.mainScreen().bounds.height - frame.origin.y)
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(self.view).offset(bottomMargin)
            })
            self.view.layoutIfNeeded()
        }
    }
    
    private func setupToolBar() {
        self.view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        
        let itemSettings = [
            ["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon:"],
            ["imageName": "compose_add_background", "action": "add"]
        ]
        
        var index = 0
        toolBar.items = [UIBarButtonItem]()
        for dict in itemSettings{
            let imageName = dict["imageName"]!
            let action = dict["action"]!
            let item = UIBarButtonItem(imageName: imageName, target: self, action: Selector(action))
            item.customView?.tag = index
            toolBar.items?.append(item)
            toolBar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            index++
        }
        toolBar.items?.removeLast()
    }
    
    @objc private func picture() {
    UIView.animateWithDuration(CZDefaultDuration) { () -> Void in
        self.photoSelectorVC.view.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view)
        }
        self.view.layoutIfNeeded()
        }
        textView.resignFirstResponder()
        
        isShowPhotoSelectorView = true
    }
    
    @objc private func trend() {
        CZPrint(items: "trend")
    }
    
    @objc private func mention() {
        CZPrint(items: "mention")
    }
    
    @objc private func emoticon(button: UIButton) {
//        CZPrint(items: "emoticon")
        var image: UIImage?
        var selectedImage: UIImage?
        if textView.inputView == nil {
            textView.inputView = emoticonKeyboardView
            image = UIImage(named: "compose_keyboardbutton_background")
            selectedImage = UIImage(named: "compose_keyboardbutton_background_highlighted")
            
        }else{
            textView.inputView = nil
            image = UIImage(named: "compose_emoticonbutton_background")
            selectedImage = UIImage(named: "compose_emoticonbutton_background_highlighted")
        }
        button.setImage(image, forState: UIControlState.Normal)
        button.setImage(selectedImage, forState: UIControlState.Highlighted)
        textView.resignFirstResponder()
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            self.textView.becomeFirstResponder()
        }
    }
    
    @objc private func add() {
        CZPrint(items: "add")
    }
    
    private func setupTextView() {
        // 1.添加控件
        self.view.addSubview(textView)
        
        // 2.添加约束
        // 填充父控件
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
    }

    private func setupNavigationBar() {
        // 左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        // 右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        // 按钮不可用
        navigationItem.rightBarButtonItem?.enabled = false
        
        setupTitleView()
    }
    
    /// 设置导航栏的标题
    private func setupTitleView() {
        let prefix = "发微博"
        if let name = CZUserAccountViewModel.sharedInstance.userAccount?.screen_name {
            // \n 换行符
            let text = prefix + "\n" + name
            // 获取到用户名称
            let label = UILabel()
            label.textColor = UIColor.blackColor()
            label.font = UIFont.systemFontOfSize(13)
            label.numberOfLines = 0
            label.textAlignment = NSTextAlignment.Center
            
            // 创建属性文本
            let attrText = NSMutableAttributedString(string: text)
            
            // 获取用户名称的范围
            let nameRange = (text as NSString).rangeOfString(name)
            
            // 属性文本添加属性
            attrText.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange)
            attrText.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(11), range: nameRange)
            
            label.attributedText = attrText
            // 注意设置sizeToFit需要在label有内容后才可以
            label.sizeToFit()
            
            navigationItem.titleView = label
            
        } else {
            // 没有用户名称
            navigationItem.title = prefix
        }
    }
    
    /// 发布微博
    @objc private func sendStatus() {
        let text = textView.emoticonNameText()
        if statusMaxLength - text.characters.count < 0{
            SVProgressHUD.showErrorWithStatus("超出长度")
            return
        }
        
        SVProgressHUD.showWithStatus("正在发布微博...")
        
        let image = photoSelectorVC.photos.first
        CZStatusViewModel.sharedInstance.sendStatus(image,statusString:text) { (error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发布微博失败")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发布微博成功了")
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                self.close()
            })
        }
    }
    
    /// 关闭控制器
    @objc private func close() {
        self.textView.resignFirstResponder()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    private lazy var textView: CZPlaceholderTextView = {
        let tv = CZPlaceholderTextView()
        
        // 设置
        tv.backgroundColor = UIColor.brownColor()
        tv.font = UIFont.systemFontOfSize(ComposeTextFontSize)
        
        // 设置占位文本
        tv.placeholder = "请输入.."
        
        // 设置控制器成为代理监听textView文本改变
        tv.delegate = self
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        tv.alwaysBounceVertical = true
        
        return tv
    }()
    
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    private lazy var emoticonKeyboardView: CZEmoticonKeyboard = {
       let keyboard = CZEmoticonKeyboard()
        keyboard.textView = self.textView
        return keyboard
    }()

    private lazy var lengthTipLabel: UILabel = {
       let label = UILabel()
        label.textColor = UIColor.lightGrayColor()
        label.font = UIFont.systemFontOfSize(10)
        label.text = String(self.statusMaxLength)
        label.sizeToFit()
        
        return label
    }()
    
     private lazy var photoSelectorVC: CZPhotoSelectedController = CZPhotoSelectedController()
}

extension CZComposeViewController: UITextViewDelegate {
    // 文字改变
    func textViewDidChange(textView: UITextView) {
        CZPrint(items: "文字改变: \(textView.text)")
        
        // 有文字,rightBarButtonItem可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        let length = textView.emoticonNameText().characters.count
        let leftLength = statusMaxLength - length
        lengthTipLabel.text = String(leftLength)
        lengthTipLabel.textColor = leftLength < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
    }
}
